<?php

/**
 * Project: CrazyPoems
 * Author: Alexandru
 * Date: 21/10/2008
 * File: functions.poem.php
 */
 
function Hop_newPoem($title, $category, $poem, $response_to) {
  global $cookie;
    if (strlen($response_to) == 0) { $response_to = 'NULL'; }
		if (intval($cookie->admin) ==1) { $author = $_POST['author']; } else { $author = $cookie->username; }
	$c = "INSERT INTO ".TABLE_POEMS."(title, category, poem, publish_date, last_update, author, response_to, lang)";
    $c .=" values('".checkSQL($title)."', $category, '".checkSQL($poem)."','".get_current_time()."','".get_current_time()."', '".$author."', $response_to, '{$_POST['lang']}')";
    $q = mysql_query($c) or die(mysql_error().$c);
    $newId = mysql_insert_id();
    // Notify the author of the poem to wich you respond.
    if ($response_to != 'NULL') {
        Hop_notifyPoemResponse($response_to, $newId);
    }
    return $newId;
}

function Hop_editPoem($poemId, $title, $category, $poem) {
  global $cookie;
		if (intval($cookie->admin) ==1) { $author = $_POST['author']; } else { $author = $cookie->username; }
    $c = "UPDATE ".TABLE_POEMS." SET author = '".$author."', title = '".checkSQL($title)."', category = $category, poem = '".checkSQL($poem)."', last_update = '".get_current_time()."', lang = '{$_POST['lang']}' WHERE id = $poemId";
	$q = mysql_query($c) or die(mysql_error());
    return mysql_insert_id();
}

function Hop_addComment($poemId, $poemAuthor, $poemTitle, $fullname, $email, $comment) {
  global $cookie;
    // Insert comment.
    $q = mysql_query("INSERT INTO ".TABLE_COMMENTS."(poem_id, author, fullname, email, comment, publish_date) values($poemId, '".$cookie->username."','".checkSQL($fullname)."', '$email', '".checkSQL($comment)."','".get_current_time()."')") or die(mysql_error());
    $commentId = mysql_insert_id();
    // Get poem link
    $poemLink = get_link('poem', array('title' => $poemTitle, 'id' => $poemId), true);
    // Notify owner.
    if ($poemAuthor != $cookie->username) {
        $c2 = "SELECT email,fullname FROM ".TABLE_USERS." WHERE username = '$poemAuthor'";
        // echo $c2;
        $q2 = mysql_query($c2) or die(mysql_error());
        $r2 = mysql_fetch_assoc($q2);
        if ($r2) {
            $poemAuthorName = $r2['fullname'];
            $message = "Salut $poemAuthorName,\n\n";
            $message .="$fullname a comentat la poezia \"$poemTitle\", vezi comentariul: \n\n";
            $message .=$poemLink."#comment".$commentId."\n\n";
            $message .="Happy reading and writing,\n";
            $message .=MAIL_URL;
            if (mail($r2['email'], "$fullname a comentat la $poemTitle", $message, "From: \"Crazy Poems\"<no-reply@crazypoems.net>\nReply-to: \"Crazy Poems\"<no-reply@crazypoems.net>")) {
                // die('email sent');
            } else {
                // die('email not sent');
            }
        }
    }
		// Redirect.
		header("Location: ".$poemLink."#comment".$commentId);
}

function Hop_addVote($poemId) {
  global $cookie;
	global $smarty;
	$vote_error_msg = "";
	$c = "SELECT * FROM ".TABLE_POEMS_VOTES." WHERE author = '".$cookie->username."' and poem_id = $poemId";
	$q = mysql_query($c) or die(mysql_error());
	$r = mysql_fetch_assoc($q);
	if ($r) {
		// Already voted.
	} else {
		$c2 = "INSERT INTO ".TABLE_POEMS_VOTES." (poem_id, author, `date`) values($poemId, '".$cookie->username."', '".get_current_time()."')";
		$q2 = mysql_query($c2) or die(mysql_error());
		$smarty->assign('confirmation', "<p>Ai votat aceasta poezie!</p>");
	}
	// $smarty->assign('vote_error_msg', $vote_error_msg);
}

function Hop_checkVote($poemId) {
  global $cookie;
	if (isset($cookie->username) && strlen($cookie->username) > 0) {
		$c = "SELECT id FROM ".TABLE_POEMS_VOTES." WHERE author = '".$cookie->username."' and poem_id = $poemId";
		$q = mysql_query($c) or die(mysql_error());
		$r = mysql_fetch_assoc($q);
		if ($r) {
			return true;
		} else {
			return false;
		}
	} else {
		return false;
	}
}

function Hop_countVotes($poemId) {
	$c = "SELECT count(*) as votes FROM ".TABLE_POEMS_VOTES." WHERE poem_id = $poemId";
	$q = mysql_query($c) or die(mysql_error());
	$r = mysql_fetch_assoc($q);
	if ($r) {
		return $r['votes'];
	} else {
		return 0;
	}
}

function Hop_getComments($poemId) {
    $comments = array();
	$q = mysql_query("
          SELECT c.*, u.photo FROM ".TABLE_COMMENTS." AS c
            LEFT JOIN ".TABLE_USERS." AS u
            ON u.username = c.author
          WHERE poem_id = $poemId ORDER BY id") or die(mysql_error());
	while ($r = mysql_fetch_assoc($q)) {
		$tmp = array(
                  'id' => $r['id'],
                  'author' => $r['author'],
                  'fullname' => $r['fullname'],
                  'email' => $r['email'],
                  'publishDate' => $r['publish_date'],
                  'comment' => nl2br($r['comment']),
                  'photo' => Hop_getUserPhoto($r['photo']),
                );
		$comments[] = $tmp;
	}
	return $comments;    
}

function Hop_getResponsePoems($poemId) {
    $responsePoems = array();
	$q = mysql_query("SELECT id, title, author, category FROM ".TABLE_POEMS." WHERE response_to = $poemId ORDER BY id") or die(mysql_error());
    if (mysql_num_rows($q) > 0) {
        while ($r = mysql_fetch_assoc($q)) {
            $tmp = array('id' => $r['id'],
                         'title' => $r['title'],
                         'author' => $r['author'],
                         'link' => get_link('poem', array('id' => $r['id'], 'title' => $r['title'], 'category' => $r['category'])));
            $responsePoems[] = $tmp;
        }
        return $responsePoems;
    } else {
	    return "";
    }
}

function Hop_getPoem($poemId, $mode = 'short') {
    if ($mode == 'full') {
        $c = "SELECT * FROM " . TABLE_POEMS . " WHERE id = $poemId";
    } else { // short
        $c = "SELECT id, title, author, category FROM " . TABLE_POEMS . " WHERE id = $poemId";
    }
    $q = mysql_query($c) or die(mysql_error());
    $r = mysql_fetch_assoc($q);
    if ($r) {
        return $r;
    } else {
        return "";
    }
}

function Hop_notifyPoemResponse($response_to, $newId) {
  global $cookie;
    // Get author of the original poem.
    $c = "SELECT author,title FROM " . TABLE_POEMS . " WHERE id = $response_to";
    $q = mysql_query($c) or die(mysql_error());
    $r = mysql_fetch_assoc($q);
    if ($r) {
        $originalAuthor = $r['author'];
        $originalPoemTitle = $r['title'];
        // Get his info.
        $c2 = "SELECT email,fullname FROM ".TABLE_USERS." WHERE username = '$originalAuthor'";
        $q2 = mysql_query($c2) or die(mysql_error());
        $r2 = mysql_fetch_assoc($q2);
        if ($r2) {
            $originalAuthorEmail = $r2['email'];
            $originalAuthorFullname = $r2['fullname'];
            // Send email.
            $message = "Salut $originalAuthorFullname,\n\n";
            $message .=$cookie->fullname . " a scris o poezie ca raspuns la poezia ta \"$originalPoemTitle\", o poti citii la adresa: \n\n";
            $message .=MAIL_URL."poem.php?id=$newId\n\n";
            $message .="Happy reading and writing,\n";
            $message .=MAIL_URL;
            if (mail($originalAuthorEmail, $cookie->fullname . " a raspuns la $originalPoemTitle", $message, "From: \"Crazy Poems\"<no-reply@crazypoems.net>\nReply-to: \"Crazy Poems\"<no-reply@crazypoems.net>")) {
                //echo('email sent');
            } else {
                //echo('email not sent');
            }
        } else {
            die("Can't get original author info.");
        }
    } else {
        die("Can't get original author username.");
    }
}

function Hop_sameAuthorPoems($username, $currentPoemId) {
    $userPoems = array();
	$q = mysql_query("SELECT id, title, category FROM ".TABLE_POEMS." WHERE author = '$username' AND id <> $currentPoemId ORDER BY id desc limit 0,10") or die(mysql_error());
    if (mysql_num_rows($q) > 0) {
        while ($r = mysql_fetch_assoc($q)) {
            $tmp = array('id' => $r['id'], 'title' => $r['title'], 'link' => get_link('poem', array('id' => $r['id'], 'title' => $r['title'], 'category' => $r['category'])));
            $userPoems[] = $tmp;
        }
        return $userPoems;
    } else {
	    return "";
    }
}

?>
